import React, { useEffect, useMemo, useState } from 'react';
import { Card, message, Tree, Dropdown, Space, Modal, Form, Input, Select, FormInstance, Spin } from 'antd';
import type { MenuProps } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import { deleteDepartments, fetchDepartmentsList, fetchSimple, addDepartments, findDepartments, updateDepartments } from '@/store/modules/departmentStore';
import { DownOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import type { DepartmentTree, PickDepartment, Department as DepartmentType } from '@/type/DepartmentType';
import './Department.scss';


const { confirm } = Modal;

const Department:React.FunctionComponent = () => {
  const dispatch = useDispatch();
  const departments = useSelector((state: any) => state.departmentStore.departments);
  const simples = useSelector((state: any) => state.departmentStore.simples);
  const [form] = Form.useForm<FormInstance<PickDepartment>>();
  const items: MenuProps['items'] = [{ label: '添加部门', key: '1' }, { label: '编辑部门', key: '2' }, { label: '删除部门', key: '3' }];
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [edit, setEdit] = useState<boolean>(false);
  const title = useMemo(() => edit ? '编辑部门' : '添加部门', [edit]);
  const [formData, setFormData] = useState<PickDepartment>({} as PickDepartment);
  const [loading, setLoading] = useState<boolean>(false);

  /**
   * @description 获取部门列表的回调函数
   * */
  const fetchDepartments = async () => {
    try {
      setLoading(true);
      await dispatch(fetchDepartmentsList()).unwrap();
    } catch (rejectedValueOrSerializedError: any) {
      message.error(rejectedValueOrSerializedError);
    } finally {
      setLoading(false);
    }
  };

  /**
   * @description 获取部门负责人的回调函数
   * */
  const fetchSimpleList = async () => {
    try {
      await dispatch(fetchSimple());
    } catch (rejectedValueOrSerializedError: any) {
      message.error(rejectedValueOrSerializedError);
    }
  };
  /**
   * @description 点击确定按钮的回调函数
   * */
  const handleOk = async () => {
    if (edit) {
      try {
        const newFormData = { ...formData, ...form.getFieldsValue() };
        setFormData(newFormData);
        const updateMessage = await dispatch(updateDepartments(newFormData)).unwrap();
        await fetchDepartments();
        setIsModalOpen(false);
        message.success(updateMessage);
      } catch (rejectedValueOrSerializedError: any) {
        message.error(rejectedValueOrSerializedError);
      }
    } else {
      try {
        const newFormData = { ...formData, ...form.getFieldsValue() };
        setFormData(newFormData);
        const addMessage = await dispatch(addDepartments(newFormData)).unwrap();
        await fetchDepartments();
        setIsModalOpen(false);
        message.success(addMessage);
      } catch (rejectedValueOrSerializedError: any) {
        message.error(rejectedValueOrSerializedError);
      }
    }

  };

  /**
   * @description 点击取消按钮的回调函数
   * */
  const handleCancel = () => {
    setIsModalOpen(false);
  };


  /**
   * @description 下拉菜单点击的回调函数
   * */
  const handleMenuClick = async (key: string, nodeData: DepartmentTree) => {
    if (key === '1') {
      setEdit(false);
      setIsModalOpen(true);
      setFormData({ ...formData, pid: nodeData.id });
    } else if (key === '2') {
      try {
        const departmentDetail = await dispatch(findDepartments(nodeData.id)).unwrap();
        setEdit(true);
        setIsModalOpen(true);
        setFormData(departmentDetail);
        form.setFieldsValue(departmentDetail);
      } catch (rejectedValueOrSerializedError: any) {
        message.error(rejectedValueOrSerializedError);
      }

    } else {
      confirm({
        title: '温馨提示',
        icon: <ExclamationCircleFilled />,
        content: `确认删除${nodeData.name}吗?`,
        okText: '确定',
        cancelText: '取消',
        onOk: async (): Promise<void> => {
          try {
            const deleteMessage = await dispatch(deleteDepartments(nodeData.id)).unwrap();
            await fetchDepartments();
            message.success(deleteMessage);
          } catch (rejectedValueOrSerializedError: any) {
            message.error(rejectedValueOrSerializedError);
          }
        },
      });
    }
  };


  const afterOpenChange = (open: boolean) => {
    if (!open) {
      form.resetFields();
    }
  };

  const selectSimple = (value: number) => {
    setFormData({ ...formData, managerId: value });
  };


  const titleRender = (nodeData: any) => {
    return (
      <div className="tree">
        <div className="left">
          <span className="name">{nodeData.name}</span>
        </div>
        <div className="center">
          <span className="managerName">{nodeData.managerName}</span>
        </div>
        <div className="right">
          <Dropdown menu={{ items, onClick: (event) => handleMenuClick(event.key, nodeData) }}>
            <Space>
              <span>操作</span>
              <DownOutlined />
            </Space>
          </Dropdown>
        </div>
      </div>
    );
  };

  const renterTree = () => {
    if (loading) {
      return (
        <div className="loading">
          <Spin spinning={loading} size="large">加载中</Spin>
        </div>
      );
    } else {
      return (
        <>
          <Tree treeData={departments} defaultExpandAll={true} fieldNames={{ title: 'name', key: 'id', children: 'children' }} titleRender={titleRender} showLine></Tree>
        </>
      );
    }
  };
  useEffect(() => {
    fetchDepartments();
    fetchSimpleList();
  }, []);

  return (
    <div className="department  layui-anim layui-anim-scale">
      <Card>
        {
          renterTree()
        }
      </Card>
      <Modal width={700} title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} afterOpenChange={afterOpenChange}>
        <Form form={form} clearOnDestroy>
          <Form.Item<DepartmentType> label="部门名称" name="name">
            <Input placeholder="请输入部门名称"></Input>
          </Form.Item>
          <Form.Item<DepartmentType> label="部门编码" name="code">
            <Input placeholder="请输入部门编码"></Input>
          </Form.Item>
          <Form.Item<DepartmentType> label="部门负责" name="managerId">
            <Select placeholder="请选择部门负责人" options={simples} onSelect={selectSimple}></Select>
          </Form.Item>
          <Form.Item<DepartmentType> label="部门介绍" name="introduce">
            <Input.TextArea rows={4} placeholder="请输入部门介绍" maxLength={6} />
          </Form.Item>
        </Form>
      </Modal>

    </div>
  );
};

export default Department;
